import parser from 'yargs-parser'
import { help } from './help'
import { build } from './script/build'
import { ArgvArguments } from './interface'

const argv: Partial<ArgvArguments> = parser(process.argv.slice(2), {
  alias: {
    entry: ['e'],
    output: ['o'],
    help: ['h'],
    version: ['v'],
  },
  boolean: ['es', 'preset-react', 'only-remove-type-imports', 'disable-babel'],
  array: ['files'],
})

const main = async () => {
  try {
    const version = require('../package.json').version
    if (argv.v) {
      console.log()
      console.log(` Version \x1b[32;1m ${version}\x1b[0m`)
      console.log()
      return
    }
    if (argv.h) {
      return help()
    }

    const entry = argv.entry || argv.e || 'src'
    const output = argv.output || argv.o || 'app'
    let files = argv.files
    if (typeof files === 'string') {
      files = [files]
    }

    const isEsmodules = Reflect.has(argv, 'es')
      ? Reflect.get(argv, 'es')
      : false
    const isReact = Reflect.has(argv, 'presetReact')
      ? Reflect.get(argv, 'presetReact')
      : false
    const onlyRemoveTypeImports = Reflect.has(argv, 'onlyRemoveTypeImports')
      ? Reflect.get(argv, 'onlyRemoveTypeImports')
      : false
    const disableBabel = Reflect.has(argv, 'disableBabel')
      ? Reflect.get(argv, 'disableBabel')
      : false

    const options = {
      isReact,
      isEsmodules,
      files,
      onlyRemoveTypeImports,
      outDir: output,
      disableBabel,
    }
    if (argv._[0] === 'build') {
      await build(entry, options)
    }
    if (argv._[0] === 'watch') {
      console.log('暂时没写watch')
    }
  } catch (err) {
    console.log(err)
    process.exit()
  }
}
main()
